#include <stdint.h>
#include <stdbool.h>
#include <assert.h>
#include <string.h>
#include <stdlib.h>

#include <video_cmd.h>
#include "debug/debug.h"

struct video_cmd* video_cmd_alloc(void)
{
	struct video_cmd* video_cmd = malloc(sizeof(struct video_cmd));
	if (video_cmd == NULL)
	{
		print_error("video frame cmd alloc failed.");
		return video_cmd;
	}

	bzero(video_cmd, sizeof(*video_cmd));
	video_cmd->data_total_size = VIDEO_ACTION_DATA_MAX_LEN;

	pthread_spin_init(&video_cmd->spin, 0);
	return video_cmd;

}

void video_cmd_free(struct video_cmd* cmd)
{
	if (cmd == NULL)
		return;

	assert(!cmd->ref_cnt);

	free(cmd);
}

void video_cmd_get(struct video_cmd* cmd)
{
	pthread_spin_lock(&cmd->spin);
	cmd->ref_cnt++;
	pthread_spin_unlock(&cmd->spin);

}

void video_cmd_put(struct video_cmd* cmd)
{
	if (!cmd)
		return;

	pthread_spin_lock(&cmd->spin);
	cmd->ref_cnt--;
	assert(cmd->ref_cnt >= 0);
	pthread_spin_unlock(&cmd->spin);

	
	if (!cmd->ref_cnt)
	{
		pthread_spin_destroy(&cmd->spin);
		if (cmd->put_cmd)
			cmd->put_cmd(cmd->handle, cmd);
		else
		{
			video_cmd_free(cmd);
		}
	}
}